package com.weizengquan.ereader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;

import org.json.JSONException;
import org.json.JSONObject;

import com.weizengquan.ereader.TranslateTask;
import com.weizengquan.ereader.db.DictionaryData;

import android.app.Activity;  
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.content.Intent;
import android.graphics.Color;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;


public class TestActivity extends Activity implements OnTouchListener{
	
	private static final String TAG = "TranslateTask";
	
	private Handler guiThread;
	private ExecutorService transThread;
	private Runnable updateTask;
	private Future transPending;
	
	private String original;
	private String from="en";
	private String to="zh-CN";
	private TextView translated;
	private DictionaryData dictionaryData;
	
    GestureDetector gestureDetector;

    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);
        
        EditText editText=(EditText)findViewById(R.id.editText1);
    	editText.setOnTouchListener(this);   	
    	
    	translated=(TextView)findViewById(R.id.textView);
    	gestureDetector = new GestureDetector(this, new GestureListener(editText));
    	dictionaryData=new DictionaryData(this);
		dictionaryData.getWritableDatabase();
       
    }
    
    
	public   boolean  onTouch(View v, MotionEvent e) {
		return gestureDetector.onTouchEvent(e);
	}
	
	
	private class GestureListener extends SimpleOnGestureListener {
		
	    private EditText editText;

	    public GestureListener(EditText editText) {
			// TODO Auto-generated constructor stub
	    	this.editText=editText;
		}

	    // event when double tap occurs
	    @Override
	    public boolean onDoubleTap(MotionEvent e) {
	    	Editable s1;
	    	EditText editText=(EditText)findViewById(R.id.editText1);
	    	TextView textView=(TextView)findViewById(R.id.textView);
	    	
	    	int start=editText.getSelectionStart();
	    	int end=editText.getSelectionEnd();
	    	int currentCursor=start;
	    	int t=editText.getText().length();

	    	while(--start>0){
	    		char a=editText.getText().toString().charAt(start);
	    		if(a==' ' || a=='\n')
	    			break;
	    	}

	    	while(end<editText.getText().length()){
	    		char b=editText.getText().toString().charAt(end);
	    		if(b==' '|| b=='\n')
	    			break;
	    		else
	    			end++;	
	    	}
	    	
	    	
	        if(end > start) 
	        {
	            s1 = (Editable) editText.getText().subSequence(start, end);
	        }else
	        {
	            s1 = (Editable) editText.getText().subSequence(end, start);
	        }
	        
	        SpannableStringBuilder style=new SpannableStringBuilder(editText.getText());
	        style.setSpan(new ForegroundColorSpan(Color.RED),start,end,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
	        editText.setText(style);
	        editText.setSelection(currentCursor);
	        
	        original=s1.toString();
	        //String s2=doTranslate(s1.toString());
	        String s2=doTranslateFromDictionary(s1.toString());
	        textView.setText(s1+":"+s2);
	        
	        return true;
	    }
	    
	    private String doTranslateFromDictionary(String original){
	    	
		      return dictionaryData.queryWord(null,original);
	    	
	    }

	    
		private String doTranslate(String original) {
		      HttpURLConnection con = null;
		      String result = "error";
		      //remove the space before and behind the word

		      try {
		          // Build RESTful query for Google API
		          String q = URLEncoder.encode(original, "UTF-8");
		          URL url = new URL(
		                "http://ajax.googleapis.com/ajax/services/language/translate"
		                      + "?v=1.0" + "&q=" + q + "&langpair=" + from
		                      + "%7C" + to);
		          con = (HttpURLConnection) url.openConnection();
		          con.setReadTimeout(10000 /* milliseconds */);
		          con.setConnectTimeout(15000 /* milliseconds */);
		          con.setRequestMethod("GET");
		          con.addRequestProperty("Referer",
		                "http://www.pragprog.com/titles/eband3/hello-android");
		          con.setDoInput(true);

		          // Start the query
		          con.connect();

		          // Read results from the query
		          BufferedReader reader = new BufferedReader(
		                new InputStreamReader(con.getInputStream(), "UTF-8"));
		          String payload = reader.readLine();
		          reader.close();

		          // Parse to get translated text
		          JSONObject jsonObject = new JSONObject(payload);
		          result = jsonObject.getJSONObject("responseData")
		                .getString("translatedText")
		                .replace("&#39;", "'")
		                .replace("&amp;", "&");


		       } catch (IOException e) {
		          Log.e(TAG, "IOException", e);
		       } catch (JSONException e) {
		          Log.e(TAG, "JSONException", e);
		       } finally {
		          if (con != null) {
		             con.disconnect();
		          }
		       }
			return result;
		}

		private void translateFromEnglishToChinese(String o) {
			// TODO Auto-generated method stub
			String result;
			guiThread = new Handler();
		    transThread = Executors.newSingleThreadExecutor();

		      // This task does a translation and updates the screen
		      updateTask = new Runnable() { 
		         public void run() {
		            // Get text to translate
		            String original2 = original;

		            // Cancel previous translation if there was one
		            if (transPending != null)
		               transPending.cancel(true); 

		            // Take care of the easy case
		            if (original2.length() == 0) {
		               translated.setText("error"); 
		            } else {
		               // Let user know we're doing something
		            	translated.setText("translating"); 
		               // Begin translation now but don't wait for it
		               try {
		                  TranslateTask translateTask = new TranslateTask( 
		                        TestActivity.this, // reference to activity
		                        original2, // original text
		                        "en", // from language
		                        "zh-CN" // to language
		                  );
		                  transPending = transThread.submit(translateTask); 
		               } catch (RejectedExecutionException e) {
		                  // Unable to start new task
		                  translated.setText("error"); 
		               }
		            }
		         }
		      };
			
		}
	}
	
	  public void setTranslated(String text) {
	      guiSetText(translated, text);
	   }
	
	
	   /** All changes to the GUI must be done in the GUI thread */
	   private void guiSetText(final TextView view, final String text) {
	      guiThread.post(new Runnable() {
	         public void run() {
	            view.setText(text);
	         }
	      });
	   }


}
